import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutterlib/common/config/config.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/datacenter/user_center.dart';
import 'package:flutterlib/common/net/interceptors/response_interceptor.dart';
import 'package:flutterlib/common/utils/sp_utils.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:thrio/thrio.dart';

import 'interceptors/header_interceptor.dart';
import 'interceptors/log_interceptor.dart';


///http请求
class HttpManager {
  static final int CONNECR_TIME_OUT = 1000 * 10;
  static final int RECIVE_TIME_OUT = 1000 * 10;
  static final CONTENT_TYPE_JSON = "application/json;charset=UTF-8";
  static final CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static Dio _dio;

  static Map<String, CancelToken> _cancelTokens =
      new Map<String, CancelToken>();

  HttpManager._internal() {
    initDio();
  }

  Dio getDio(){
    return _dio;
  }

  static HttpManager _httpManger = HttpManager._internal();

  factory HttpManager() {
    return _httpManger;
  }

  ///配置dio
  void initDio() {
    _dio = Dio();

    _dio.interceptors.add(new HeaderInterceptors());

    // final TokenInterceptors _tokenInterceptors = new TokenInterceptors();
    // _dio.interceptors.add(_tokenInterceptors);
    _dio.interceptors.add(new ResponseInterceptors());

    _dio.interceptors.add(new LogsInterceptors());
    _dio.interceptors.add(InterceptorsWrapper(
      onError: (DioError err) {
        if(err?.response?.statusCode == 401){
          //网关认证失败，有可能是jwt过期，也有可能是rsa过期，rsa过期通过重新进app解决，这里不解决
          if (currentUser != null) {
            ChannelDataCenter().invoke("refreshJWT");
          }
        }

        trueDebugPrint('flutterhttp Dio error with request: ${err.request.uri}');
        trueDebugPrint('flutterhttp Request data: ${err.request.data}');
        trueDebugPrint('flutterhttp Dio error: ${err.message}');
        return err;
      },
    ));

//    _dio.interceptors.add(new ResponseInterceptors());
    /// 添加拦截器
//    _dio.interceptors.add(new MyIntercept());

    // 配置dio实例
//    _dio.options.baseUrl = "http://10.150.20.86/xloan-app-api/";
   _dio.options.baseUrl = Config.API_DEV_HOST;
    _dio.options.connectTimeout = CONNECR_TIME_OUT; //5s
    _dio.options.receiveTimeout = RECIVE_TIME_OUT;
    // _dio.options.receiveDataWhenStatusError = true;
//    _dio.options.contentType = CONTENT_TYPE_FORM;

//代理设置
//     if (Config.DEBUG) {
// //      _dio.interceptors
// //          .add(WhLogInterceptor(requestBody: true, responseBody: true));
//       //此处可以增加配置项，留一个设置代理的用户给测试人员配置，然后动态读取
//
// //      print("--prox----${proxy}----${SpUtils.getBool(SpConstanst.httpProxyEnable)}=====-");
//       if(proxy!=null&&proxy!=""&&SpUtils.getBool("")) {
//         (_dio.httpClientAdapter as DefaultHttpClientAdapter)
//             .onHttpClientCreate =
//             (client) {
//           // config the http client
//           client.findProxy = (uri) {
//             //proxy all request to localhost:8888
//             return "PROXY " + SpUtils.getString("");
//           };
//
//
//           client.badCertificateCallback =
//               (X509Certificate cert, String host, int port) => true;
//           // you can also create a new HttpClient to dio
//           // return new HttpClient();
//         };
//       }
//     } else {
//       //证书配置，忽略证书
//       String PEM = "XXXXX"; // certificate content
//       (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//           (client) {
//         client.badCertificateCallback =
//             (X509Certificate cert, String host, int port) {
//           return true; //返回 true 表明 忽略 证书校验
//         };
//       };
//     }
  }

}

